﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Microsoft.Win32;
using OfficeOpenXml;
using static OfficeOpenXml.ExcelErrorValue;
using System.Diagnostics;
using System.Net;
using System.Reflection.Metadata; 
using FileOper.org;
using MySql.Data.MySqlClient;

namespace FileOper
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private DataTable nowtable;

        public MainWindow()
        {
            InitializeComponent();
        }

        private void testBtnClick0(object sender, RoutedEventArgs e)
        {
            DriveInfo[] drives = DriveInfo.GetDrives();
            var msg = "";
            foreach (var drive in drives)
            {
                msg = msg + "," + drive.Name;

            }
            //MessageBox.Show("找到一个U盘：" + msg);
            this.showText.Text = msg + FileUtil.add(1,2);
        }
        private void testBtnClick1(object sender, RoutedEventArgs e)
        {
            SaveFileDialog save = new SaveFileDialog();
            // save.InitialDirectory = defaultFolderPath;
            save.FileName = "temp.txt";//获取用户选择的文件路径和文件名
            // save.Filter = "Excel files (*.xlsx)|*.xlsx|All files (*.*)|*.*";//文件格式

            if ((bool)save.ShowDialog())
            {
                string filePath = save.FileName;
                StreamWriter sw = new StreamWriter(filePath, false, Encoding.UTF8);//实例化StreamWriter 
                sw.WriteLine(this.showText.Text);
                sw.Flush();
                sw.Close();


            }



        }
        private void testBtnClick2(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            //openFileDialog.Filter = "Excel Files|*.xlsx;*.xls";
            if (openFileDialog.ShowDialog() == true)
            {
                string filePath = openFileDialog.FileName;
                StreamReader sr = new StreamReader(filePath, Encoding.UTF8);
                string txtFileContent = sr.ReadToEnd();
                this.showText.Text = txtFileContent;
                sr.Close();
            }
        }

        private void writeExcelClick(object sender, RoutedEventArgs e)
        {
            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "Excel Files|*.xlsx";
            if (saveFileDialog.ShowDialog() == true)
            {
                string filePath = saveFileDialog.FileName;
                WriteExcelFile(filePath, this.nowtable);
                MessageBox.Show("File saved successfully!");
            }
        }
        private void testBtnClick5(object sender, RoutedEventArgs e)
        {

            Random r = new Random();//random是类
            int num = r.Next(0, 10);
            Trace.WriteLine("xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx");


        }
        private void readExcelClick(object sender, RoutedEventArgs e)
        {
            OpenFileDialog openFileDialog = new OpenFileDialog();
            openFileDialog.Filter = "Excel Files|*.xlsx;*.xls";
            if (openFileDialog.ShowDialog() == true)
            {
                string filePath = openFileDialog.FileName;
                DataTable dataTable = ReadExcelFile(filePath);
                this.nowtable = dataTable;
                string st = "";
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    for (int j = 0; j < dataTable.Columns.Count; j++)
                    {
                        if (j > 0)
                        {
                            st += ",";
                        }
                        st += dataTable.Rows[i][j];
                    }
                    st += "\r\n";
                }
                this.showText.Text = st;
            }

        }

        private DataTable ReadExcelFile(string filePath)
        {
            //设置许可证上下文为非商业版，如果你使用的是商业版许可证，则设置为 LicenseContext.Commercial
            ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
            DataTable dataTable = new DataTable();
            using (ExcelPackage package = new ExcelPackage(new FileInfo(filePath)))
            {

                ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
                bool hasHeader = false; // adjust it accordingly( i've mentioned that this is a simple approach)
                foreach (var firstRowCell in worksheet.Cells[1, 1, 1, worksheet.Dimension.End.Column])
                {

                    dataTable.Columns.Add(hasHeader ? firstRowCell.Text : $"Column {firstRowCell.Start.Column}");
                }
                var startRow = hasHeader ? 2 : 1;
                for (int rowNum = startRow; rowNum <= worksheet.Dimension.End.Row; rowNum++)
                {
                    var wsRow = worksheet.Cells[rowNum, 1, rowNum, worksheet.Dimension.End.Column];
                    DataRow row = dataTable.NewRow();
                    foreach (var cell in wsRow)
                    {
                        row[cell.Start.Column - 1] = cell.Text;
                    }
                    dataTable.Rows.Add(row);
                }
            }
            return dataTable;
        }

        private void WriteExcelFile(string filePath, DataTable dataTable)
        {
            //设置许可证上下文为非商业版，如果你使用的是商业版许可证，则设置为 LicenseContext.Commercial
            ExcelPackage.LicenseContext = OfficeOpenXml.LicenseContext.NonCommercial;
            using (ExcelPackage package = new ExcelPackage())
            {
                ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Sheet1");
                for (int i = 0; i < dataTable.Columns.Count; i++)
                {
                    worksheet.Cells[1, i + 1].Value = dataTable.Columns[i].ColumnName;
                }
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    for (int j = 0; j < dataTable.Columns.Count; j++)
                    {
                        worksheet.Cells[i + 2, j + 1].Value = dataTable.Rows[i][j];
                    }
                }
                package.SaveAs(new FileInfo(filePath));
            }
        }

        private void testHttpClick(object sender, RoutedEventArgs e)
        {

            Stream instream = null;
            StreamReader sr = null;
            HttpWebResponse response = null;
            HttpWebRequest request = null;
            // 准备请求...
            try
            {
                // 设置参数
                request = WebRequest.Create("http://127.0.0.1:9900/otherIoWarehouse/queryPackageByMat?materialId=2310230340") as HttpWebRequest;
                CookieContainer cookieContainer = new CookieContainer();
                request.CookieContainer = cookieContainer;
                request.AllowAutoRedirect = true;
                request.Method = "GET"; //请求方式GET或POST
                request.ContentType = "application/x-www-form-urlencoded";
                request.Headers.Add("Authorization", "Basic YWRtaW46YWRtaW4=");

/*                 
                request.ContentType = "application/json";//Http内容类型
                request.MaximumAutomaticRedirections = 1;//获取或设置请求将跟随的重定向的最大数目。
                request.AllowAutoRedirect = true;//获取或设置一个值，该值指示请求是否应跟随重定向响应。
                request.SendChunked = false;//获取或设置一个值，该值指示是否将数据分段发送到 Internet 资源。
                request.CookieContainer = Cookies;//获取或设置与此请求关联的cookie。
                request.UserAgent = "cps";//获取或设置 User-agent HTTP 标头的值
                request.Timeout = 18000;//获取或设置请求的超时值。 设置请求超时时间，单位为毫秒 
*/
                //发送请求并获取相应回应数据
                response = request.GetResponse() as HttpWebResponse;
                //直到request.GetResponse()程序才开始向目标网页发送Post请求
                instream = response.GetResponseStream();
                sr = new StreamReader(instream, Encoding.UTF8);
                //返回结果网页（html）代码
                string content = sr.ReadToEnd();
                string err = string.Empty;
                this.showText.Text = content;
            }
            catch (Exception ex)
            { 
                Trace.Write(ex.Message);
                this.showText.Text = ex.Message;
            }
        } 

        private void testBtnClick8(object sender, RoutedEventArgs e)
        {

            string connectionString = "Server=localhost;Database=liaoy_mes;User Id=root;Password=123456;";
            try
            {
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    string query = "SELECT * FROM test_cs "; // 使用你实际的表名
                    MySqlCommand cmd = new MySqlCommand(query, conn);
                    MySqlDataReader reader = cmd.ExecuteReader();

                    string dataSt = "";
                    while (reader.Read())
                    {
                        // 使用实际的列名
                        if(dataSt.Length > 0)
                        {
                            dataSt +=  ",";
                        }
                        dataSt += reader["code"].ToString(); 

                    }
                    this.showText.Text = dataSt;                  

                    conn.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
            } 

        }


        private void testInertBtnClick(object sender, RoutedEventArgs e)
        {

            string connectionString = "Server=localhost;Database=liaoy_mes;User Id=root;Password=123456;";
            try
            {
                using (MySqlConnection conn = new MySqlConnection(connectionString))
                {
                    conn.Open();
                    DateTime currentTime = DateTime.UtcNow;
                    long timestamp = (long)(currentTime.Subtract(new DateTime(1970, 1, 1))).TotalMilliseconds;
                    string addSql = "insert into test_cs(code,name) values('"+ timestamp + "','2222')"; // 使用你实际的表名
                    MySqlCommand cmd1 = new MySqlCommand(addSql, conn);
                    object objResult = cmd1.ExecuteScalar();
                    if (objResult == null)
                    { 
                        cmd1.Dispose();
                    }

                    conn.Close();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error: " + ex.Message);
            }

        }
    }
}